package com.ld.shieldsb.common.web.util.server;

import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Set;

import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.Query;
import javax.servlet.ServletContext;

import lombok.extern.slf4j.Slf4j;

@Slf4j
/**
 * server信息工具类（仅处理的tomcat的，其他未测试）
 * 
 * @ClassName ServerUtil
 * @author <a href="mailto:donggongai@126.com" target="_blank">吕凯</a>
 * @date 2018年12月14日 上午9:17:49
 *
 */
public class WebServerUtil {

    public static String getHost() {
        try {
            String host = InetAddress.getLocalHost().getHostAddress();
            return host;
        } catch (Exception e) {
            log.error("获取服务器host出错！", e);
        }
        return "";
    }

    /**
     * 获取服务url
     * 
     * @Title getServerURL
     * @author 吕凯
     * @date 2018年12月14日 上午9:18:37
     * @return
     * @throws MalformedObjectNameException
     * @throws NullPointerException
     * @throws UnknownHostException
     *             String
     */
    public static String getServerURL(ServletContext servletContext) {
        return getWebServer(servletContext).getUrl();
    }

    /**
     * 获取服务器端口
     * 
     * @Title getTomcatPort
     * @author 吕凯
     * @date 2018年12月14日 上午9:19:07
     * @return int
     */
    public static int getTomcatPort() {
        try {
            MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer();
            Set<ObjectName> objectNames = beanServer.queryNames(new ObjectName("*:type=Connector,*"),
                    Query.match(Query.attr("protocol"), Query.value("HTTP/1.1")));
            ObjectName objectName = objectNames.iterator().next();
            String port = objectName.getKeyProperty("port");
            return Integer.valueOf(port);
        } catch (Exception e) {
            log.error("获取端口出错！", e);
        }
        return -1;
    }

    public static WebServerModel getWebServer(ServletContext servletContext) {
        WebServerModel webServer = new WebServerModel();
        webServer.setHost(getHost());
        webServer.setProjectName(servletContext.getContextPath());
        webServer.setPort(getTomcatPort());
        return webServer;
    }

}
